// ==================== 图纸导入 Composable ====================
// 应用层服务模块
// 职责：提供图纸导入功能的Vue组合式API

import { ref, reactive, computed } from 'vue'
import { DrawingImportService } from '@/services/DrawingImportService.js'
import { useLayerStore, useViewportStore } from '@/stores'

/**
 * 图纸导入 Composable
 * 提供图纸导入、渲染和管理的组合式API
 */
export function useDrawingImport(canvasRef = null) {
  // ==================== 响应式状态 ====================
  const isImporting = ref(false)
  const importProgress = ref(0)
  const importError = ref(null)
  const importedDrawings = ref([])
  
  // ==================== 服务实例 ====================
  let importService = null
  
  // ==================== 初始化服务 ====================
  const initializeServices = () => {
    if (!importService) {
      importService = new DrawingImportService({
        maxFileSize: 50 * 1024 * 1024, // 50MB
        allowedFormats: ['image', 'pdf', 'cad']
      })
    }
    
    // 检查canvasRef是否存在且有效
    const canvas = canvasRef && typeof canvasRef === 'object' && 'value' in canvasRef ? canvasRef.value : canvasRef
    
  }
  
  // ==================== 图纸导入 ====================
  
  /**
   * 导入图纸文件
   * @param {Object} options - 导入选项
   * @returns {Promise<Object>} 导入结果
   */
  const importDrawing = async (options = {}) => {
    try {
      initializeServices()
      
      isImporting.value = true
      importProgress.value = 0
      importError.value = null
      
      // 打开文件选择器
      const file = await importService.openFileSelector({
        multiple: options.multiple || false
      })
      
      if (!file) {
        throw new Error('用户取消选择文件')
      }
      
      console.log('选择的文件:', file.name, file.type, file.size)
      
      // 导入图纸文件
      const result = await importService.importDrawing(file)
      
      if (result.success) {
        console.log('图纸导入成功:', result.data)
        
        // 添加到已导入图纸列表
        importedDrawings.value.push(result.data)
        
        // 将图纸作为底图添加到背景层
        const layerStore = useLayerStore()
        
        // 找到背景层
        const backgroundLayer = layerStore.getLayerByType('background')
        if (backgroundLayer) {
          // 将图纸对象添加到背景层，并标记为底图
          for (const layerData of result.data.layers) {
            for (const object of layerData.objects) {
              // 标记为底图，不可选中
              const backgroundObject = {
                ...object,
                isBackground: true,
                selectable: false,
                layerId: 'background',
                drawingId: result.data.id, // 添加图纸ID标识
                visible: true,
                opacity: 1.0
              }
              // 计算原来的宽高比
              const originalAspectRatio = object.width / object.height
              // 图片视图需要在中间完整显示
              const viewportStore = useViewportStore()
              const viewport = viewportStore.viewport
              const viewportAspectRatio = viewport.width / viewport.height
              if (originalAspectRatio > viewportAspectRatio) {
                backgroundObject.width = viewport.width
                backgroundObject.height = viewport.width / originalAspectRatio
              } else {
                backgroundObject.width = viewport.height * originalAspectRatio
                backgroundObject.height = viewport.height
              }
              backgroundObject.x = (viewport.width - backgroundObject.width) / 2
              backgroundObject.y = (viewport.height - backgroundObject.height) / 2
              layerStore.addObjectToLayer('background', backgroundObject)
            }
          }
        }
        
        
        importProgress.value = 100
        
        return {
          success: true,
          data: result.data,
          message: '图纸导入成功'
        }
        
      } else {
        throw new Error(result.error)
      }
      
    } catch (error) {
      console.error('导入图纸时发生错误:', error)
      importError.value = error.message
      
      return {
        success: false,
        error: error.message,
        message: '图纸导入失败'
      }
    } finally {
      isImporting.value = false
    }
  }
  
  /**
   * 批量导入图纸
   * @param {Array<File>} files - 文件数组
   * @returns {Promise<Array>} 导入结果数组
   */
  const importMultipleDrawings = async (files) => {
    const results = []
    
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      
      try {
        initializeServices()
        
        // 导入单个文件
        const result = await importService.importDrawing(file)
        
        if (result.success) {
          // 添加到已导入图纸列表
          importedDrawings.value.push(result.data)
          
          // 将图纸数据添加到图层存储
          const layerStore = useLayerStore()
          
          // 为每个图纸图层创建图层
          for (const layerData of result.data.layers) {
            const newLayer = {
              id: layerData.id,
              name: layerData.name,
              type: layerData.type,
              visible: layerData.visible,
              locked: layerData.locked,
              opacity: layerData.opacity,
              order: layerStore.layers.length
            }
            
            layerStore.createLayer(newLayer)
            
            for (const object of layerData.objects) {
              layerStore.addObjectToLayer(layerData.id, object)
            }
          }
          
        }
        
        results.push({
          success: result.success,
          fileName: file.name,
          data: result.data,
          error: result.error
        })
        
        // 更新进度
        importProgress.value = ((i + 1) / files.length) * 100
        
      } catch (error) {
        results.push({
          success: false,
          fileName: file.name,
          error: error.message
        })
      }
    }
    
    return results
  }
  
  // ==================== 图纸管理 ====================
  
  /**
   * 获取已导入的图纸
   * @returns {Array} 图纸数组
   */
  const getImportedDrawings = () => {
    return importedDrawings.value
  }
  
  /**
   * 移除图纸
   * @param {string} drawingId - 图纸ID
   */
  const removeDrawing = (drawingId) => {
    const index = importedDrawings.value.findIndex(d => d.id === drawingId)
    if (index > -1) {
      const drawing = importedDrawings.value[index]
      
      
      // 从图层存储中移除
      const layerStore = useLayerStore()
      for (const layer of drawing.layers) {
        layerStore.deleteLayer(layer.id)
      }
      
      // 从已导入列表中移除
      importedDrawings.value.splice(index, 1)
      
      console.log(`图纸已移除: ${drawing.name}`)
    }
  }
  
  /**
   * 清空所有图纸
   */
  const clearAllDrawings = () => {
    
    // 从图层存储中移除
    const layerStore = useLayerStore()
    const drawingLayers = layerStore.layers.filter(layer => 
      ['image', 'pdf', 'cad'].includes(layer.type)
    )
    
    for (const layer of drawingLayers) {
      layerStore.deleteLayer(layer.id)
    }
    
    // 清空已导入列表
    importedDrawings.value = []
    
    console.log('所有图纸已清空')
  }
  
  // ==================== 图层控制 ====================
  
  /**
   * 设置图纸图层可见性
   * @param {string} layerId - 图层ID
   * @param {boolean} visible - 是否可见
   */
  const setDrawingLayerVisibility = (layerId, visible) => {

  }
  
  /**
   * 设置图纸图层透明度
   * @param {string} layerId - 图层ID
   * @param {number} opacity - 透明度 (0-1)
   */
  const setDrawingLayerOpacity = (layerId, opacity) => {

  }
  
  // ==================== 渲染控制 ====================
  
  /**
   * 重新渲染所有图纸
   */
  const rerenderAll = () => {

  }
  
  /**
   * 获取渲染统计信息
   * @returns {Object} 渲染统计
   */
  const getRenderStats = () => {

    return null
  }
  
  // ==================== 计算属性 ====================
  
  const hasImportedDrawings = computed(() => {
    return importedDrawings.value.length > 0
  })
  
  const importedDrawingCount = computed(() => {
    return importedDrawings.value.length
  })
  
  const isImportingInProgress = computed(() => {
    return isImporting.value
  })
  
  const currentImportProgress = computed(() => {
    return importProgress.value
  })
  
  const lastImportError = computed(() => {
    return importError.value
  })
  
  // ==================== 清理 ====================
  
  /**
   * 清理资源
   */
  const cleanup = () => {

    
    if (importService) {
      importService.clearDrawingData()
      importService = null
    }
    
    importedDrawings.value = []
    isImporting.value = false
    importProgress.value = 0
    importError.value = null
  }
  
  // ==================== 返回API ====================
  return {
    // 状态
    isImporting: isImportingInProgress,
    importProgress: currentImportProgress,
    importError: lastImportError,
    importedDrawings,
    hasImportedDrawings,
    importedDrawingCount,
    
    // 方法
    importDrawing,
    importMultipleDrawings,
    getImportedDrawings,
    removeDrawing,
    clearAllDrawings,
    setDrawingLayerVisibility,
    setDrawingLayerOpacity,
    rerenderAll,
    getRenderStats,
    cleanup
  }
}
